package com.test26_比较器;

import org.junit.Test;

import java.util.Arrays;
import java.util.Comparator;

/**
 * Comparator接口
 * 设置时没考虑到排序需求
 */
public class Demo03_Comparator {

    /**
     * 使用自定义比较规则
     */
    @Test
    public void test1() {
        Book3[] books = new Book3[] {
                new Book3("Java从入门到项目实战", 99.8),
                new Book3("Python从入门到项目实战", 89.7),
                new Book3("Go语言从入门到项目实战", 96.3)
        };
        Arrays.sort(books, new BookComparator());  // 数组排序处理
        Arrays.stream(books).forEach(System.out::println);
    }

    /**
     * 通过Lambda实现自定义比较规则
     */
    @Test
    public void test2() {
        Book3[] books = new Book3[] {
                new Book3("Java从入门到项目实战", 99.8),
                new Book3("Python从入门到项目实战", 89.7),
                new Book3("Go语言从入门到项目实战", 96.3)
        };
        Comparator<Book3> comparator = (o1, o2) -> {
            if (o1.getPrice() > o2.getPrice()) {
                return 1;
            } else if (o1.getPrice() < o2.getPrice()) {
                return -1;
            }
            return 0;
        };
        Arrays.sort(books, comparator.reversed());  // 排序反转
        Arrays.stream(books).forEach(System.out::println);
    }
}

class Book3 {
    private String title;
    private double price;

    public Book3(String title, double price) {
        this.title = title;
        this.price = price;
    }

    public String getTitle() {
        return title;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return "【Book】图书名称：" + this.title + "、图书价格：" + this.price;
    }
}

/**
 * 提供有专属的比较器实现类
 */
class BookComparator implements Comparator<Book3> {

    @Override
    public int compare(Book3 o1, Book3 o2) {
        if (o1.getPrice() > o2.getPrice()) {
            return 1;
        } else if (o1.getPrice() < o2.getPrice()) {
            return -1;
        }
        return 0;
    }
}
